class LoginPage < Page
  
  description %{
    A login screen for secure pages
  }
  
  attr_reader :login_error
  
  @login_error = false
  
  def process(request, response)
    if request.post?
      # If the login is successfull, set the session and redirect to the return_url or homepage
      if response.session[:website_user_id] = WebsiteUser.authenticate(request.parameters[:login][:email], request.parameters[:login][:password])
        response.redirect request.session[:return_url] || Radiant::Config['secure_pages.welcome_page']
      else
        @login_error = true
        super(request, response)
      end
    else
      super(request, response)
    end
  end
  
  def cache?
    false
  end
  
  %{ All login related tags life inside this one }
  tag "login" do |tag|
    tag.expand
  end
  
  tag "login:form" do |tag|
    results =  %Q(<form action="#{url}" method="post" class="#{ tag.attr[:class] }">)
    results << tag.expand
    results << %Q(</form>)
  end
  
  tag "login:if_error" do |tag|
    tag.expand if @login_error
  end
  
  tag "login:email" do |tag|
    %Q(<input type="text" id="login_email" name="login[email]" class="#{ tag.attr[:class] }" />)
  end
  
  tag "login:password" do |tag|
    %Q(<input type="password" id="login_password" name="login[password]" class="#{ tag.attr[:class] }" />)
  end  
  
  tag "login:submit" do |tag|
    %Q(<input type="submit" value="#{ tag.attr[:value] || "Login" }" />)
  end 
  
  
  
end